import React, { useState, useContext, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import { AppState } from "../App";
import "../css/loader.css";
import "../css/songwarm.css";
import { Flex, Progress } from "antd";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faThumbsUp, faDonate } from "@fortawesome/free-solid-svg-icons";

const SearchResults = () => {
  const App = useContext(AppState);
  const [num, setNum] = useState(0);
  const itemsPerPage = 3;
  const [currentPage, setCurrentPage] = useState(1);
  const [showAdmin, setShowAdmin] = useState(true);
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const keyword = searchParams.get("keyword");
  const [allData, setAllData] = useState([]);
  const [results, setResults] = useState([]);
  const [Useramount, setUseramount] = useState();
  const [loading, setLoading] = useState(false);
  const [Pcount, setPcount] = useState("");
  const [Balance, setBalance] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        let adminProposals = [];
        let userProposals = [];
        if (App.Foundationcontract) {
          const adminCount = await App.Foundationcontract.requestsNumber();
          for (let i = 0; i < adminCount; i++) {
            const proposal = await App.Foundationcontract.requestions(i);
            adminProposals.push({ ...proposal, type: "admin" });
          }
          const userCount = await App.Foundationcontract.userrequestsNumber();
          for (let i = 0; i < userCount; i++) {
            const proposal = await App.Foundationcontract.userrequestions(i);
            userProposals.push({ ...proposal, type: "user" });
          }
        }
        setAllData([...adminProposals, ...userProposals]);
      } catch (error) {
        console.error("Error fetching proposals:", error);
      }
    };
    fetchData();
  }, [App.Foundationcontract]);

  useEffect(() => {
    setLoading(true);
    const handleSearch = () => {
      if (keyword === "") {
        alert("请输入搜索内容");
      } else {
        try {
          const filteredData = allData.filter(
            (proposal) =>
              (proposal.description &&
                proposal.description.includes(keyword)) ||
              (proposal.tittle && proposal.tittle.includes(keyword)) ||
              (proposal.recipient && proposal.recipient.includes(keyword))
          );

          // 计算剩余时间并设置到结果中
          const updatedResults = filteredData.map((item) => ({
            ...item,
            remainingTime: calculateRemainingTime(item.endTime, item.completed),
          }));

          setResults(updatedResults);
        } catch (error) {
          console.error("Error searching:", error);
        } finally {
          setLoading(false);
        }
      }
    };
    handleSearch();
  }, [keyword, allData]);

  useEffect(() => {
    const getBal = async () => {
      try {
        const Balance = await App.Foundationcontract.getBalance();
        const totalContributors = await App.Foundationcontract.contributorsNumber();
        setBalance(Balance);
        setPcount(totalContributors);
      } catch (error) {
        console.log(error);
      }
    };
    getBal();
  }, [App.Foundationcontract]);

  useEffect(() => {
    const interval = setInterval(() => {
      setResults((prevData) =>
        prevData.map((item) => ({
          ...item,
          remainingTime: calculateRemainingTime(item.endTime, item.completed),
        }))
      );
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  const calculateRemainingTime = (endTime, completed) => {
    if (completed) {
      return "已结束";
    }
    const now = new Date().getTime();
    const end = endTime * 1000;
    const distance = end - now;

    if (distance < 0) {
      return "已结束";
    }
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
  };

  const calculatePercentage = (votersNumber) => {
    const percentage = (votersNumber / (Pcount / 2)) * 100;
    return percentage > 50 ? 100 : percentage;
  };

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;

  const filteredResults = showAdmin
    ? results.filter((result) => result.type === "admin")
    : results.filter((result) => result.type === "user");
  const currentItems = filteredResults.slice(indexOfFirstItem, indexOfLastItem);

  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(filteredResults.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const toggleDisplay = (type) => {
    setShowAdmin(type === "admin");
    setCurrentPage(1);
  };

  const Vote = async (nums) => {
    try {
      const tx = await App.Foundationcontract.voteRequest(nums);
      await tx.wait();
      alert("投票成功");
      setNum(num + 1);
    } catch (error) {
      if (error.message === "YOu must be contributor") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  const Donate = async (id) => {
    try {
      const tx = await App.Foundationcontract.executeRequest(id);
      await tx.wait();
      alert("捐赠成功！");
      setNum(num + 1);
    } catch (error) {
      if (error.message === "execution reverted: You already Voted") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  return (
    <div>
      <div className="songwarmBtnDiv">
        <button
          onClick={() => toggleDisplay("admin")}
          className={`search-toggle-button ${showAdmin ? "active" : ""}`}
        >
          显示管理员
        </button>
        <button
          onClick={() => toggleDisplay("user")}
          className={`search-toggle-button ${!showAdmin ? "active" : ""}`}
        >
          显示用户
        </button>
      </div>
      <div className="new-layout">
        {loading && allData.length === 0 ? (
          <div className="loader"></div>
        ) : null}
        {currentItems.length !== 0 ? (
          currentItems.map((e, id) => {
            const photos = e.photo ? e.photo.split(",") : [];
            const percentage = calculatePercentage(
              e.votersNumber ? Number(e.votersNumber.toString()) : 0
            );
            return (
              <div className="item-container" key={id}>
                <div className="left-content">
                  <div className="left_img">
                    <img
                      src={
                        photos.length > 0
                          ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${photos[0]}`
                          : "/images/love.jpg"
                      }
                      style={{ width: 99.9, height: 79.9 }}
                    />
                  </div>
                  <div className="left_right">
                    <div className="description">
                      <p>{e.description}</p>
                    </div>

                    <div className="category">
                      <p>
                        {e.tittle}--
                        {e.targetMoney
                          ? Number(e.targetMoney.toString())
                          : 0}{" "}
                        爱心币(所需金额)
                      </p>
                      <p>剩余时间--{e.remainingTime}</p>
                    </div>

                    <div className="button-container">
                      <button
                        onClick={() => Vote(Number(e.uniqueid.toString()))}
                        className="voted_button"
                      >
                        <FontAwesomeIcon icon={faThumbsUp} />
                        {e.votersNumber ? e.votersNumber.toString() : 0}
                        <span className="tooltiptext">投票</span>
                      </button>
                      <button
                        onClick={() => Donate(Number(e.uniqueid.toString()))}
                        className="voted_button"
                      >
                        <FontAwesomeIcon icon={faDonate} />
                        <span className="tooltiptext">捐赠</span>
                      </button>
                      <Flex gap="small" wrap>
                        <Progress
                          type="dashboard"
                          percent={percentage}
                          width={53}
                          strokeWidth={8}
                        />
                      </Flex>
                    </div>
                  </div>
                </div>
                <div className="right-content">
                  {photos.slice(0, 3).map((photo, idx) => (
                    <Link
                      key={idx}
                      to={`/header/songwarm/${e.uniqueid}`}
                      className="image-link"
                    >
                      <img
                        src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${photo}`}
                        alt={`Proposal Photo ${idx + 1}`}
                      />
                      {idx === 2 && photos.length > 3 && (
                        <div className="overlay">
                          <h2 className="overlay-text">
                            +{photos.length - 3} 张
                          </h2>
                          <p className="overlay-text">查看所有图片</p>
                        </div>
                      )}
                    </Link>
                  ))}
                </div>
              </div>
            );
          })
        ) : (
          <div className="flex items-center justify-center nonDIv">
            <div className="title-font sm:text-2xl text-xl font-medium text-gray-900 text-black">
              没有相关内容。
            </div>
          </div>
        )}
      </div>
      {currentItems.length !== 0 && (
        <div className="pagination-container">
          <button
            className={`pagination-button ${
              currentPage === 1 ? "disabled" : ""
            }`}
            onClick={() => handleClick(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          {pageNumbers.map((number) => (
            <button
              key={number}
              className={`pagination-button ${
                currentPage === number ? "active" : ""
              }`}
              onClick={() => handleClick(number)}
            >
              {number}
            </button>
          ))}
          <button
            className={`pagination-button ${
              currentPage === pageNumbers.length ? "disabled" : ""
            }`}
            onClick={() => handleClick(currentPage + 1)}
            disabled={currentPage === pageNumbers.length}
          >
            下一页
          </button>
        </div>
      )}
    </div>
  );
};

export default SearchResults;
